package com.boot.controller;

import com.boot.entity.Purchapply;
import com.boot.entity.PurchapplyCheck;
import com.boot.entity.User;
import com.boot.service.IPurchaseRequestService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购申请Controller
 */
@Controller
@RequestMapping("/purchaseRequest")
public class PurchaseRequestController {

    @Autowired
    private IPurchaseRequestService service;

    @RequestMapping("/list")
    public String listPurchaseApply(String purchapplyStatus, String documentNumber,String powerName,HttpServletRequest request, Integer pageIndex, Integer pageSize, Model model) {
        if (pageIndex == null) {
            pageIndex = 1;
        }
        if (pageSize == null) {
            pageSize = 6;
        }

        PageHelper.startPage(pageIndex, pageSize);

        try {
            if ("all".equals(purchapplyStatus)) {
                purchapplyStatus = null;
            }
            if (StringUtils.isEmpty(purchapplyStatus)) {
                purchapplyStatus = null;
            }
            if (StringUtils.isEmpty(documentNumber)) {
                documentNumber = null;
            }
            if (StringUtils.isEmpty(powerName)) {
                powerName = null;
            }
            User user = (User) request.getSession().getAttribute("loginUser");

            if(user == null){
                throw new RuntimeException("用户未登录");
            }
            if(StringUtils.isEmpty(user.getCompanyId())){
                throw new RuntimeException("用户公司id为空 ");
            }

            List<Purchapply> purchaseApplyList = service.listPurchaseApply(purchapplyStatus, documentNumber,powerName,user.getCompanyId());
            model.addAttribute("purchaseApplyList", purchaseApplyList);
            model.addAttribute("purchapplyStatus", purchapplyStatus);
            model.addAttribute("documentNumber", documentNumber);
            model.addAttribute("powerName", powerName);

            int count = service.getPurchapplyRequestCount(purchapplyStatus, documentNumber,powerName,user.getCompanyId());
            int pageNum = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
            model.addAttribute("count", count); //查询数量

            model.addAttribute("pageNum", pageNum); //分页数量
            model.addAttribute("currentPage", pageIndex); //当前页面
            model.addAttribute("pageSize", pageSize); //页面数据条数
            return "purchapplyList";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

    @RequestMapping("/getDetail/{purchapplyId}")
    public String getDetail(@PathVariable("purchapplyId") Integer purchapplyId, Model model) {
        try {

            //采购需求详情
            Map<String, Object> purchaseMap = service.getPurchaseDetail(purchapplyId);
            //详情中id对应的name
            Map<String, Object> nameMap = service.getDetailName(purchapplyId);
            if (nameMap != null && !nameMap.isEmpty()) {
                purchaseMap.putAll(nameMap);
            }
            //煤质要求
            Map<String, Object> coalQualityMap = service.getCoalQualityMap(purchapplyId);

            //审核记录
            List<Map<String, Object>> auditRecords = service.getPurchaseApplyAuditList(purchapplyId);
            //创建记录
            Map<String, Object> createRecord = service.getPurchaseApplyCreateInfo(purchapplyId);
            createRecord.put("operation", "创建");
            createRecord.put("check_opinion", "");
            createRecord.put("check_remark", "");
            auditRecords.add(0, createRecord);

            model.addAttribute("purchaseMap", purchaseMap);
            model.addAttribute("coalQualityMap", coalQualityMap);
            model.addAttribute("auditRecords", auditRecords);
            return "purchapplyDetail";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

    @RequestMapping(value = "/getDetail/audit", method = RequestMethod.POST)
    @ResponseBody
    public Object auditPurchaseApply(PurchapplyCheck purchapplyCheck, HttpServletRequest request, Model model) {
        try {
            //判断登录人员角色，
            //若为监察人员且审核表中没有该需求审核通过记录，则直接进行审核，添加采购审核记录,若已有审核通过的记录，则无法再审核
            //若为管理人员则需先在审核表中查询是否已有审核通过记录，若无，则不能提前审核，若有，则修改采购需求审核状态，添加审核记录。
            User user = (User) request.getSession().getAttribute("loginUser");
            Map<String, Object> map = new HashMap<>();

            if (user == null) {
                map.put("msg", "用户信息为空");
                map.put("code", 601);
            } else if (!StringUtils.isEmpty(user.getId()) && !StringUtils.isEmpty(user.getCompanyId())) {
                purchapplyCheck.setOperatorId(user.getId());
                purchapplyCheck.setCompanyId(user.getCompanyId());
                if (!StringUtils.isEmpty(user.getRole())) {
                    //获取审核通过记录条数
                    String checkOpinion = "agree";
                    int count = service.getAuditAgreeCount(purchapplyCheck.getPurchapplyId(), checkOpinion);
                    switch (user.getRole()) {
                        //监察人员
                        case 2:
                            if (count == 0) {
                                Boolean flag = service.auditPurchaseApply(purchapplyCheck);
                                if (flag) {
                                    map.put("msg", "审核成功");
                                    map.put("code", 200);
                                } else {
                                    map.put("msg", "审核失败");
                                    map.put("code", 601);
                                }
                            } else {
                                map.put("msg", "已有监察人员审核通过记录，不能再次审核");
                                map.put("code", 601);
                            }
                            break;
                        //管理人员
                        case 3:
                            if (count > 0 ) {
                                if(count < 2){

                                Boolean flag1 = service.auditPurchaseApply(purchapplyCheck);
                                String status;
                                if ("agree".equals(purchapplyCheck.getCheckOpinion())) {
                                    status = "published";
                                } else {
                                    status = "rejected";
                                }
                                Boolean flag2 = service.updatePurchapplyStatus(purchapplyCheck.getPurchapplyId(), status);
                                if (flag1 && flag2) {
                                    map.put("msg", "审核成功");
                                    map.put("code", 200);
                                } else {
                                    map.put("msg", "审核失败");
                                    map.put("code", 601);
                                }
                                }else {
                                    map.put("msg", "已有管理人员审核，不能重复审核");
                                    map.put("code", 601);
                                }
                            } else {
                                map.put("msg", "无上一级审核通过记录，不能提前审核");
                                map.put("code", 601);
                            }
                            break;
                        default:
                            map.put("msg", "权限不足，无法审核");
                            map.put("code", 403);
                            break;
                    }
                }
            }
            return map;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

}
